package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"shop-api/consts"
	"shop-api/internal/model"
	"shop-api/internal/server"
	"time"
)

func UpdateUser(c *gin.Context) {
	userID := c.GetUint("user_id")
	req := new(model.User)
	if err := c.ShouldBindJSON(&req); err != nil {
		Resp(c, nil, err)
		return
	}

	req.ID = userID
	info, err := server.UpdateUser(req)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	fmt.Println(info.Birthday)
	t, err := time.Parse(time.RFC3339, info.Birthday)
	if err != nil {
		Resp(c, nil, err)
		return
	}
	info.Birthday = t.Format(time.DateOnly)
	Resp(c, info, nil)
	return
}

func Login(c *gin.Context) {
	req := new(server.LoginReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		Resp(c, nil, err)
		return
	}

	//TODO:校验手机号格式
	if req.Phone == "" {
		Resp(c, nil, fmt.Errorf("手机号不能为空"))
		return
	}

	if req.Code == "" && req.Type == consts.LoginTypeCode {
		Resp(c, nil, fmt.Errorf("验证码不能为空"))
		return
	}

	if req.Pwd == "" && req.Type == consts.LoginTypePwd {
		Resp(c, nil, fmt.Errorf("密码不能为空"))
		return
	}

	info, err := server.Login(req)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	Resp(c, info, nil)
	return
}

func checkReq(req *server.LoginReq) error {
	//TODO:校验手机号格式
	if req.Phone == "" {
		return fmt.Errorf("手机号不能为空")
	}
	if req.Code == "" {
		return fmt.Errorf("验证码不能为空")
	}
	if req.Pwd == "" {
		return fmt.Errorf("密码不能为空")
	}
	return nil
}

func Register(c *gin.Context) {
	req := new(server.LoginReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		Resp(c, nil, err)
		return
	}

	err := checkReq(req)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	info, err := server.Register(req)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	Resp(c, info, nil)
	return
}

func ForgetPwd(c *gin.Context) {
	req := new(server.LoginReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		Resp(c, nil, err)
		return
	}

	err := checkReq(req)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	info, err := server.ForgetPwd(req)
	if err != nil {
		Resp(c, nil, err)
		return
	}

	Resp(c, info, nil)
	return

}
